<template>
  <div class="customers-data">
    <div class="search-content">
      <el-input v-model="searchObj.store_name" placeholder="请输入经销商名称" clearable class="input w200"></el-input>
      <el-input v-model="searchObj.pc_id" placeholder="卡券id" clearable class="input w200"></el-input>
      <!-- <el-input v-model="searchObj.pc_name" placeholder="卡券名称	" clearable class="input w200"></el-input> -->
      <el-autocomplete v-model="searchObj.pc_name" class="input w200" value-key="pc_name" :trigger-on-focus="false" :fetch-suggestions="querySearchAsync" placeholder="卡券名称" @select="handleSelect"></el-autocomplete>

      <el-select v-model="searchObj.project_class_id" clearable placeholder="卡券分类">
        <el-option
          v-for="item in typeList"
          :key="item.id"
          :label="item.project_class_name"
          :value="item.id"
        ></el-option>
      </el-select>

      <!-- <el-date-picker
        v-model="value"
        type="daterange"
        start-placeholder="创建开始日期"
        end-placeholder="创建结束日期"
        :default-time="['00:00:00', '23:59:59']"
        value-format="yyyy-MM-dd"
        :unlink-panels="true"
      ></el-date-picker>-->

      <el-date-picker
        v-model="searchObj.start_time"
        type="date"
        placeholder="创建开始日期"
        value-format="yyyy-MM-dd"
        default-time="00:00:00"
      ></el-date-picker>
      <el-date-picker
        v-model="searchObj.end_time"
        type="date"
        placeholder="创建结束日期"
        value-format="yyyy-MM-dd"
        default-time="23:59:59"
      ></el-date-picker>

      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
    </div>
    <div class="logList" style="width:100%;">
      <el-table
        :data="aList"
        border
        style="width: 100%"
        id="table"
        :height="oHeight"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
      >
        <template v-for="item in tableProp">
          <el-table-column
            :prop="item.prop"
            :label="item.label"
            :show-overflow-tooltip="true"
            :key="item.prop"
          ></el-table-column>
        </template>
      </el-table>

      <div class="bottom-flex" type="flex">
        <div class="grid-content bg-purple">
          <el-button type="primary" class="exportButton">
            <el-link type="primary" style="color: #fff" :href="href">导出</el-link>
          </el-button>
        </div>
        <pagination
          :arr="aList"
          :total="total"
          :currentPage="currentPage"
          :handleSizeChange="handleSizeChange"
          :handleCurrentChange="handleCurrentChange"
        ></pagination>
      </div>
    </div>
  </div>
</template>

<script>
import pagination from "@/components/pagination/pagination.vue";
import { resize } from "@/common/js/height.js";
import Qs from "qs";

export default {
  data() {
    return {
      restaurants: [],
      oHeight: 800,
      href: "",
      agentName: [], //经销商下拉框
      value: "", // 时间范围
      aList: [],
      tableProp: [
        {
          label: "序号",
          prop: "index"
        },
        {
          label: "所属经销商",
          prop: "store_name"
        },
        {
          label: "卡券ID",
          prop: "pc_id"
        },
        {
          label: "卡券名称",
          prop: "pc_name"
        },
        {
          label: "卡券分类",
          prop: "project_class_name"
        },
        {
          label: "抵扣金额",
          prop: "deduction_amount"
        },
        {
          label: "创建数量",
          prop: "pc_sum"
        },
        {
          label: "剩余数量",
          prop: "pc_remaining"
        },
        {
          label: "发放数量",
          prop: "pc_send_num"
        },
        {
          label: "创建时间",
          prop: "pc_addtime"
        },
        {
          label: "截止时间",
          prop: "pc_endtime"
        },
        {
          label: "状态",
          prop: "pc_state_name"
        }
      ],
      typeList: [],
      total: 1,
      currentPage: 1,
      storeName: "",
      searchObj: {
        //该变量定义查询传参
        pageSize: localStorage.getItem("eachNum")
          ? parseInt(localStorage.getItem("eachNum"))
          : 10,
        page: 1,
        storeName: "",
        curpage: 1,
        project_class_id: "",
        pc_id: "",
        pc_name: "",
        start_time: "",
        end_time: ""
      },
      downloadLoading: false, // 控制导出按钮
      filename: "所有卡券",
      autoWidth: "",
      bookType: "xlsx"
    };
  },
  components: {
    pagination
  },
  watch: {
    aList: {
      deep: true,
      handler() {
        let obj = {};
        for (let i in this.searchObj) {
          if (this.searchObj[i]) {
            obj[i] = JSON.parse(JSON.stringify(this.searchObj[i]));
          }
        }
        obj.is_export = 1;
        obj = Qs.stringify(obj);
		let isServer = this.$store.state.isServer;
		if(isServer){
			let host = location.origin;
			host = host.replace('admin','api');
			this.href = host + "/admin/statistics/index.php?act=couponStatistics&op=allCoupon&" + obj;
		}else{
			this.href = "http://api.chejj.cn/admin/statistics/index.php?act=couponStatistics&op=allCoupon&" + obj;
		}
      }
    }
  },
  methods: {
    querySearchAsync(queryString, cb){
      console.log(queryString)
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      console.log(results)
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.pc_name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
        console.log(item);
        console.log(this.searchObj.pc_name);
    },
    //获取卡券名称关键词联想
    getrestaurantsList(){
      var that = this;
      this.$http
        .post(
          "/admin/statistics/index.php?act=couponStatistics&op=couponNameSearch"
        ).then(res=>{
          if (res.code == 1) {
            that.restaurants = res.data
          }
        })
    },
    // 获取卡券数据
    getList() {
      var that = this;
      this.searchObj.curpage = that.currentPage;
      this.$http
        .post(
          "/admin/statistics/index.php?act=couponStatistics&op=allCoupon",
          this.searchObj
        )
        .then(
          res => {
            if (res.code == 1) {
              this.aList = res.data.list;
              this.total = parseInt(res.data.totalCount);
            } else {
              alert(res.msg);
            }
          },
          err => {
            alert(err);
          }
        );
    },
    // 获取卡券分类
    getType() {
      this.$http
        .post(
          "/crm/coupons/index.php?act=projectCoupon&op=getProjectClass"
        )
        .then(
          res => {
            // console.log(res);
            if (res.code == 1) {
              this.typeList = res.data;
            } else {
              alert(res.msg);
            }
          },
          err => {
            alert(err);
          }
        );
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.searchObj.page = 1;
      this.getList();
    },
    reset() {
      //重置搜索列表
      //1、获取搜索的内容
      for (let i in this.searchObj) {
        this.searchObj[i] = "";
      }
      this.searchObj.pageSize = localStorage.getItem("eachNum")
        ? parseInt(localStorage.getItem("eachNum"))
        : 10;
      this.currentPage = 1;
      this.searchObj.page = 1;

      //2、获取内容列表
      this.getList();
    },
    //每页数据
    handleCurrentChange: function(val) {
      this.currentPage = val;
      this.searchObj.page = val;
      /*请求数据*/
      this.getList();
    },
    //分组一页多少数据
    handleSizeChange(val) {
      this.currentPage = 1;
      this.searchObj.page = 1;
      localStorage.setItem("eachNum", val);
      this.searchObj.pageSize = val;
      /*请求数据*/
      this.getList();
    },
    // 导出表格
    handleDownload() {
      this.downloadLoading = true;
      import("@/common/js/Export2Excel").then(excel => {
        let tHeader = [];
        let filterVal = [];

        this.tableProp.map(value => {
          tHeader.push(value.label);
          filterVal.push(value.prop);
        });
        const list = this.aList;
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  },
  created() {
    //页面刷新就执行
    resize(this);
    this.getList();
    this.getType();
    this.getrestaurantsList();
  }
};
</script>

<style scoped lang="scss">
.exportButton {
  margin-top: 10px;
  margin-left: 10px;
}
.bottom-flex {
  display: flex;
  justify-content: space-between;
}
</style>
